package com.tang.provider.netty;

import com.tang.provider.annotation.RpcService;
import com.tang.provider.netty.codec.json.JSONDecoder;
import com.tang.provider.netty.codec.json.JSONEncoder;
import com.tang.provider.register.ServerRegister;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author Tang
 * @classname NettyServer
 * @description [ TODO ]
 * @date 2021/1/19 22:47
 */
@Slf4j
@Component
public class NettyServer implements ApplicationContextAware, InitializingBean {

    private Map<String, Object> serviceMap = new HashMap<>(8);

    private static final NioEventLoopGroup bossGroup = new NioEventLoopGroup(4);
    private static final NioEventLoopGroup workerGroup = new NioEventLoopGroup(8);

    @Value("${rpc.server.address}")
    private String serverAddress;

    @Resource
    public ServerRegister serverRegister;

    @Override
    public void afterPropertiesSet() throws Exception {
        // 启动 netty server
        start();
    }

    private void start() {
        NettyServerHandler handler = new NettyServerHandler(this.serviceMap);
        ServerBootstrap bootstrap = new ServerBootstrap();
        try {
            bootstrap.channel(NioServerSocketChannel.class)
                    .group(bossGroup, workerGroup)
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            pipeline.addLast(new IdleStateHandler(30, 30, 60, TimeUnit.SECONDS));
                            pipeline.addLast(new JSONEncoder());
                            pipeline.addLast(new JSONDecoder());
                            pipeline.addLast(handler);
                        }
                    });
            String[] split = serverAddress.split(":");
            ChannelFuture channelFuture = bootstrap.bind(split[0], Integer.parseInt(split[1])).sync();
            log.info("netty server 启动成功!服务监听在:{}端口",split[1]);
            serverRegister.register(serverAddress);
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        // 取出标记了注解的对象，放入map
        Map<String, Object> beansWithAnnotation = applicationContext.getBeansWithAnnotation(RpcService.class);
        beansWithAnnotation.forEach((key,value) ->{
            Class<?> valueClass = value.getClass();
            Class<?>[] interfaces = valueClass.getInterfaces();
            for (Class<?> item : interfaces) {
                //                接口          实例
                serviceMap.put(item.getName(), value);
                log.info("加载服务类:{}",item.getName());
            }
        });
        log.info("已加载全部接口:{}", serviceMap);
    }
}